import React, { useEffect, useRef, useState } from 'react'
import { Button, Form, Input, Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import './register.css'

interface RegisterFormData {
  phone: string
  password: string
  code: string
}

const COUNTDOWN_SECONDS = 60

const Register: React.FC = () => {
  const [form] = Form.useForm<RegisterFormData>()
  const [sending, setSending] = useState<boolean>(false)
  const [secondsLeft, setSecondsLeft] = useState<number>(0)
  const timerRef = useRef<number | null>(null)
  const navigate = useNavigate()

  const isCounting = secondsLeft > 0

  useEffect(() => {
    if (!isCounting) return
    timerRef.current = window.setInterval(() => {
      setSecondsLeft((s) => {
        if (s <= 1) {
          if (timerRef.current) window.clearInterval(timerRef.current)
          return 0
        }
        return s - 1
      })
    }, 1000)
    return () => {
      if (timerRef.current) window.clearInterval(timerRef.current)
    }
  }, [isCounting])

  const handleSendCode = async (): Promise<void> => {
    const phone = form.getFieldValue('phone')
    if (!phone || String(phone).trim().length !== 11) {
      Toast.show({ icon: 'fail', content: '请先填写正确的手机号' })
      return
    }
    if (isCounting) return
    try {
      setSending(true)
      const resp = await fetch('http://localhost:5000/api/auth/send-code', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone })
      })
      const data = await resp.json()
      if (!resp.ok) {
        throw new Error(data?.message || '发送验证码失败')
      }
      Toast.show({ icon: 'success', content: '验证码已发送' })
      setSecondsLeft(COUNTDOWN_SECONDS)
    } catch (e) {
      Toast.show({ icon: 'fail', content: (e as Error).message || '发送验证码失败' })
    } finally {
      setSending(false)
    }
  }

  const handleSubmit = async (values: RegisterFormData): Promise<void> => {
    if (!values.phone || values.phone.length !== 11) {
      Toast.show({ icon: 'fail', content: '手机号格式不正确' })
      return
    }
    if (!values.password || values.password.length < 6) {
      Toast.show({ icon: 'fail', content: '密码至少6位' })
      return
    }
    if (!values.code || values.code.length < 4) {
      Toast.show({ icon: 'fail', content: '请填写验证码' })
      return
    }
    try {
      const resp = await fetch('http://localhost:5000/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone: values.phone, password: values.password, code: values.code })
      })
      const data = await resp.json()
      if (!resp.ok) {
        throw new Error(data?.message || '注册失败')
      }
      Toast.show({ icon: 'success', content: '注册成功' })
      navigate('/login')
    } catch (e) {
      Toast.show({ icon: 'fail', content: (e as Error).message || '注册失败' })
    }
  }

  return (
    <div className="register-container">
      <div className="register-header">
        <h1 className="register-title">注册账户</h1>
        <p className="register-subtitle">填写信息并完成验证</p>
      </div>

      <Form
        form={form}
        onFinish={handleSubmit}
        layout="vertical"
        className="register-form"
        initialValues={{ phone: '', password: '', code: '' }}
      >
        <Form.Item
          name="phone"
          label="手机号"
          rules={[
            { required: true, message: '请输入手机号' },
            { len: 11, message: '手机号必须为11位' },
          ]}
        >
          <Input placeholder="请输入手机号" clearable />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码至少6个字符' },
          ]}
        >
          <Input placeholder="请输入密码" type="password" clearable />
        </Form.Item>

        <Form.Item
          name="code"
          label="验证码"
          
          rules={[{ required: true, message: '请输入验证码' }]}
        >
          <div className="code-row">
            <Input placeholder="请输入验证码" clearable />
            <Button
              size="mini"
              color="primary"
              fill="outline"
              className="send-code-btn"
              onClick={handleSendCode}
              disabled={isCounting || sending}
            >
              {isCounting ? `${secondsLeft}s` : '发送验证码'}
            </Button>
          </div>
        </Form.Item>

        <div className="register-actions">
          <Button type="submit" color="primary" size="large" block>
            完成注册
          </Button>
          <Button
            style={{ marginTop: 8 }}
            fill="none"
            size="small"
            onClick={() => navigate('/login')}
          >
            返回登录
          </Button>
        </div>
      </Form>
    </div>
  )
}

export default Register


